package com.example.service;

import com.example.entity.InitResponse;
import com.example.entity.MoveResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class BattleService {

    private static final String INIT_URL = "http://localhost:4000/play/init";
    private static final String MOVE_URL = "http://localhost:4000/play/move";
//    private static final String TOKEN = System.getenv("TOKEN");
    private static final String TOKEN = "66c6deb1925b31ccb748b608";

    public static void main(String[] args) {
        BattleService service = new BattleService();
        service.startBattle();
    }

    public void startBattle() {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            String initResponse = sendInitRequest(client);

            InitResponse response = parseResponseInit(initResponse);
            System.out.println(response.toString());
            if (response.getCode() == 10000) {
                // 这里替换为自己的移动
                int[][] moves = new int[][]{{2, 0}, {3, 0}};

                while (true) {
                    String moveResponseStr = sendMovesRequest(client, moves);
                    MoveResponse moveResponse = parseResponseMove(moveResponseStr);

                    switch (moveResponse.getCode()) {
                        case 10001: // 当前落子成功，对方也落子成功，到你的回合下棋
                            System.out.println("Opponent moved, your turn to move.");
                            // 更新 `moves` 数据并继续游戏逻辑
                            moves = getNextMove(moveResponse.getBoard());
                            break;

                        case 10002: // 出现胜利者，可以退出程序
                            System.out.println("Winner determined, exiting.");
                            return;

                        case 20000: // 错误落子，重新落子
                            System.out.println("Invalid move, please try again.");
                            moves = getCorrectedMove();
                            break;

                        case 30000: // 当前落子超时了，对方落子成功，继续落子
                            System.out.println("Move timed out, opponent moved, your turn again.");
                            moves = getNextMove(moveResponse.getBoard());
                            break;

                        default: // 其他未处理的 code
                            System.out.println("Unexpected code received: " + moveResponse.getCode());
                            return;
                    }
                }
            } else {
                System.out.println("Failed to initialize the battle.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 伪代码方法，用于获取下一个移动的坐标
    private int[][] getNextMove(int[][] board) {
        // 计算并返回下一个移动的坐标
        return new int[][]{{3, 1}, {4, 1}}; // 示例
    }

    // 伪代码方法，用于获取修正后的移动坐标
    private int[][] getCorrectedMove() {
        // 返回修正后的移动坐标
        return new int[][]{{3, 2}, {4, 2}}; // 示例
    }


    private InitResponse parseResponseInit(String initResponse) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(initResponse, InitResponse.class);
    }
    private MoveResponse parseResponseMove(String moveResponse) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(moveResponse, MoveResponse.class);
    }

    private String sendInitRequest(CloseableHttpClient client) throws Exception {
        HttpPost request = new HttpPost(INIT_URL);
        String json = "{\"token\":\"" + TOKEN + "\"}";
        StringEntity entity = new StringEntity(json);
        request.setEntity(entity);
        request.setHeader("Content-type", "application/json");

        HttpResponse response = client.execute(request);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }

    private String sendMovesRequest(CloseableHttpClient client, int[][] moves) throws Exception {
        HttpPost request = new HttpPost(MOVE_URL);
        // 构建请求数据
        Map<String, Object> requestData = new HashMap<>();
        requestData.put("token", TOKEN);
        requestData.put("move", moves); // 示例 move

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(requestData);

        // 设置请求实体
        StringEntity entity = new StringEntity(json);
        request.setEntity(entity);
        request.setHeader("Content-type", "application/json");

        // 发送请求并获取响应
        HttpResponse response = client.execute(request);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }

}